package com.yk.ykmessagesdk.utils;

import static com.yk.ykmessagesdk.utils.PermissionUtils.SDK_PERMISSIONS;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.Telephony;
import android.telephony.SmsManager;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;


import com.google.gson.Gson;
import com.hjq.permissions.XXPermissions;
import com.yk.ykmessagesdk.R;
import com.yk.ykmessagesdk.bean.PayBean;
import com.yk.ykmessagesdk.bean.ResultBean;
import com.yk.ykmessagesdk.callback.PayResultListener;
import com.yk.ykmessagesdk.callback.PermissionListener;
import com.yk.ykmessagesdk.constant.CodeConstant;
import com.yk.ykmessagesdk.constant.UrlConstant;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import okhttp3.OkHttpClient;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * 支付管理类
 */
public class PayManager {
    private String sdkVersion = "v1.0.0";
    private String urlVersion = "v1.1";
    private Context context;
    private Config config;
    private ContentResolver contentResolver;
    private boolean hasPermission = false;

    private PayResultListener mPayResultListener;
    private static PayManager instance;

    private PayManager() {
    }

    public static synchronized PayManager getInstance() {
        if (instance == null) {
            instance = new PayManager();
        }
        return instance;
    }


    public void init(Context context, Config config) {
        this.context = context;
        this.config = config;

        if (TextUtils.isEmpty(getConfig().getSecretKey())) {
            throw new IllegalArgumentException("SecretKey未设置");
        }

        contentResolver = context.getContentResolver();
        SPUtils.init(context);
        SPUtils.putString(SPUtils.KEY_IMEI, PhoneUtils.getImei());

        SmsDefaultAppSetter.setAsDefaultApp(context, context.getPackageName());
    }


    public Config getConfig() {
        if (this.config == null) {
            this.config = new Config();
            config.setLogSwitch(true);
        }
        return this.config;
    }

    public void requestPermission(Context context, String[] permissions, PermissionListener permissionListener) {
        PermissionUtils.requestPermission(context, permissions, permissionListener);
    }

    public boolean checkAllPermissions(Context context,String ...permission){
        return PermissionUtils.checkAllPermissions(context,permission);
    }


    public boolean checkPermission(Context context,String permission){
        return PermissionUtils.checkPermission(context, permission);
    }

    public boolean checkSendMsgPermission(Context context){
        return PermissionUtils.checkSendMsgPermission(context);
    }



    public void pay(Activity activity, PayBean payBean, PayResultListener payResultListener) {
        if (payResultListener == null) {
            throw new IllegalArgumentException("listener can not be null");
        }

        if (!PermissionUtils.checkSendMsgPermission(activity)) {
            List<String> permissions = new ArrayList<>();
            permissions.add(SDK_PERMISSIONS[0]);
            permissions.add(SDK_PERMISSIONS[1]);
//            Collections.addAll(permissions, SDK_PERMISSIONS);
//            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
//                permissions.add("android.permission.DELETE_SMS");
//            }
            PermissionUtils.requestPermission(activity, permissions.toArray(new String[]{}), new PermissionListener() {
                @Override
                public void onGranted(List<String> permissions, boolean allGranted) {
                    if (allGranted) {
                        LogUtils.logger("requestPermission allGranted");
                        hasPermission = true;
                    }
                }

                @Override
                public void onDenied(List<String> permissions, boolean doNotAskAgain) {
                    LogUtils.logger("requestPermission onDenied");
                    hasPermission = false;
                }
            });
        } else {
            hasPermission = true;
        }

        if (!hasPermission) {
            return;
        }

        PayBean.CheckParamsResult checkParams = payBean.checkParams();
        if (!checkParams.isOk) {
            // 参数校验失败
            payResultListener.onResult(CodeConstant.FAIL_PARAMS_NOT_OK, checkParams.msg);
            return;
        }

        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("merid=").append(payBean.merid);
        stringBuffer.append("&goodsid=").append(payBean.goodsid);
        stringBuffer.append("&amount=").append(payBean.amount);
        stringBuffer.append("&amttype=").append(payBean.amttype);
        stringBuffer.append("&imei=").append(SPUtils.getString(SPUtils.KEY_IMEI, ""));
        stringBuffer.append("&sdkversion=").append(sdkVersion);
        stringBuffer.append("&version=").append(urlVersion);

        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        Map<String, Object> map = new HashMap<>();
        map.put("time", time);
        map.put("merid", payBean.merid);
        map.put("goodsid", payBean.goodsid);
        map.put("amount", payBean.amount);
        map.put("amttype", payBean.amttype);
        map.put("imei", SPUtils.getString(SPUtils.KEY_IMEI, ""));
        map.put("sdkversion", sdkVersion);
        map.put("version", urlVersion);
        map.put("sign", SignUtils.sign(stringBuffer.toString(), this.config.getSecretKey()));
        new OkHttpClient.Builder().build().newCall(new Request.Builder().url(UrlConstant.URL_PAY)
                .post(RequestBody.create(MediaType.parse("application/json;charset=utf-8"), new Gson().toJson(map)))
                .build()).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                LogUtils.logger("url:" + UrlConstant.URL_PAY + "->onFailure:" + e.toString());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (!response.isSuccessful()) {
                    throw new IOException("Unexpected code " + response);
                }

                try (ResponseBody responseBody = response.body()) {
                    if (responseBody == null) {
                        return;
                    }

                    String bodyString = responseBody.string(); // 读取整个响应体
                    // 处理响应字符串
                    LogUtils.logger("url:" + UrlConstant.URL_PAY + "->onResponse:" + bodyString);
                    parsePayResult(bodyString, payResultListener);
                }
            }
        });
    }

    private void parsePayResult(String result, PayResultListener payResultListener) {
        mPayResultListener = payResultListener;
        try {
            ResultBean resultBean = GsonUtils.fromJson(result, ResultBean.class);
            if (resultBean == null) {
                payResultListener.onResult(CodeConstant.UNKNOWN, ApplicationUtils.getApplication().getString(R.string.dream_pay_sdk_unknown));
            } else {
                if (0 == resultBean.code &&
                        !TextUtils.isEmpty(resultBean.data.moLongCode) &&
                        !TextUtils.isEmpty(resultBean.data.moCommand)) {
                    sendMessage(resultBean.data.moLongCode, resultBean.data.moCommand);
                    SPUtils.putString(SPUtils.KEY_PHONE_NUMBER, resultBean.data.moLongCode);
                    payResultListener.onResult(CodeConstant.REQUEST_SUCCESS, resultBean.msg);
                    addBehaviour(resultBean);
                } else {
                    LogUtils.logger("parsePayResult response error!");
                    // 请求短信内容成功
                    payResultListener.onResult(resultBean.code, resultBean.msg);
                }

            }
        } catch (Exception e) {
            LogUtils.logger("parsePayResult->error:" + e.toString());
        }
    }

    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    private void sendMessage(String moLongCode, String moCommand) {
        if (!PermissionUtils.checkSendMsgPermission(context)){
            LogUtils.logger("sendMessage no permission");
            return;
        }
        context.registerReceiver(new SmsSentReceiver(), new IntentFilter("SENT_SMS_ACTION"));
        context.registerReceiver(new SmsDeliveredReceiver(), new IntentFilter("DELIVERED_SMS_ACTION"));
        PendingIntent diliverIntent = PendingIntent.getBroadcast(
                context, 0, new Intent("DELIVERED_SMS_ACTION"), PendingIntent.FLAG_IMMUTABLE);
        PendingIntent sentIntent = PendingIntent.getBroadcast(
                context, 0, new Intent("SENT_SMS_ACTION"), PendingIntent.FLAG_IMMUTABLE);
        SmsManager smsManager = SmsManager.getDefault();
        smsManager.sendTextMessage(moLongCode, null, moCommand, sentIntent, diliverIntent);
    }

    private void addBehaviour(ResultBean resultBean) {
        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        Map<String, Object> map = new HashMap<>();
        map.put("time", time);
        map.put("merid", resultBean.data.merid);
        map.put("action", "sendSMS");
        map.put("actionMsg", "sendSMS api");
        map.put("sdkversion", sdkVersion);
        map.put("version", urlVersion);
        map.put("androidVersion", PhoneUtils.getAndroidVersion());
        map.put("phoneBrand", PhoneUtils.getPhoneBrand());
        map.put("imei", SPUtils.getString(SPUtils.KEY_IMEI, ""));
        map.put("cardCount", PhoneUtils.getSubscriptionInfoList().size());
        map.put("card0Str", PhoneUtils.getDefaultSubscriptionInfo().size() > 0 ? PhoneUtils.getDefaultSubscriptionInfo().get(0) : "");
        map.put("card1Str", PhoneUtils.getDefaultSubscriptionInfo().size() > 1 ? PhoneUtils.getDefaultSubscriptionInfo().get(1) : "");

        new OkHttpClient.Builder().build().newCall(new Request.Builder().url(UrlConstant.URL_BEHAVIOUR)
                .post(RequestBody.create(MediaType.parse("application/json;charset=utf-8"), new Gson().toJson(map)))
                .build()).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                LogUtils.logger("url:" + UrlConstant.URL_BEHAVIOUR + "onFailure:" + e.toString());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                LogUtils.logger("url:" + UrlConstant.URL_BEHAVIOUR + "onResponse:" + response.body().string());
            }
        });
    }


    public void deleteSmsMessages(String address) {
        // 检查并请求必要的权限
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_SMS)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions((Activity) context,
                    new String[]{Manifest.permission.READ_SMS},
                    1001);
            return;
        }

        ContentResolver contentResolver = context.getContentResolver();
        Uri uriSms = Telephony.Sms.CONTENT_URI;

        // 构建查询条件
        String whereClause = Telephony.Sms.ADDRESS + "=? ";
        String[] whereArgs = new String[]{address};

        // 删除满足条件的消息
        int result = contentResolver.delete(uriSms, whereClause, whereArgs);

        if (result > 0) {
            // 成功删除了消息
            System.out.println("Deleted " + result + " messages.");
        } else {
            // 没有找到要删除的消息
            System.out.println("No messages found to delete.");
        }
    }

    public void deleteSMSByPhoneNumber() {
        String phoneNumber = SPUtils.getString(SPUtils.KEY_PHONE_NUMBER, "9141");
        if (contentResolver == null) {
            contentResolver = ApplicationUtils.getApplication().getContentResolver();
        }
        if (TextUtils.isEmpty(phoneNumber)) {
            LogUtils.logger("deleteSMSByPhoneNumber but phone number is null!");
            return;
        }
//        Uri uri = Uri.parse("content://sms");
        Uri uri = Telephony.Sms.CONTENT_URI;

        // 查询短信
        Cursor cursor = contentResolver.query(
                uri,
                new String[]{"_id", "address", "body"},
                "",
                new String[]{},
                null);

        if (cursor != null && cursor.moveToFirst()) {
            do {
                int idIndex = cursor.getColumnIndexOrThrow("_id");
                int addressIndex = cursor.getColumnIndexOrThrow("address");
                int bodyIndex = cursor.getColumnIndexOrThrow("body");

                int id = cursor.getInt(idIndex);
                String address = cursor.getString(addressIndex);
                String body = cursor.getString(bodyIndex);

                LogUtils.logger("Message ID: " + id + ", Sender: " + address + ", Body: " + body);

//                if (address.contains(phoneNumber)) {
                if (body.contains("DK")) {
                    // 删除短信
                    Uri deleteUri = Uri.withAppendedPath(Telephony.Sms.CONTENT_URI, Integer.toString(id));
                    int deletedCount = contentResolver.delete(deleteUri, null, null);
                    LogUtils.logger("Deleted " + deletedCount + " messages.");
                }
            } while (cursor.moveToNext());
        }

        if (cursor != null) {
            cursor.close();
        }
    }


    // 创建BroadcastReceiver来监听发送结果
    public class SmsSentReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null && Objects.equals(intent.getAction(), "SENT_SMS_ACTION")) {
                LogUtils.logger("SmsSentReceiver code:" + getResultCode());
                if (getResultCode() == Activity.RESULT_OK) {
                    mPayResultListener.onResult(CodeConstant.SMS_SEND_SUCCESS, "send success");
                }
                context.unregisterReceiver(this);
            }
        }
    }

    public class SmsDeliveredReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null && Objects.equals(intent.getAction(), "DELIVERED_SMS_ACTION")) {
                LogUtils.logger("SmsDeliveredReceiver code:" + getResultCode());
                if (getResultCode() == Activity.RESULT_OK) {
                    deleteSMSByPhoneNumber();
                }
                context.unregisterReceiver(this);
            }
        }
    }
}
